<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;

class DashAdminAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        config(['auth.defaults.guard' => 'dash']);
        try {
            $token = JWTAuth::getToken();
            if (empty($token)) {
                return response()->json([
                    'code' => Response::HTTP_UNAUTHORIZED,
                    'message' => 'Token is not provided',
                    'data' => []
                ], Response::HTTP_UNAUTHORIZED);
            }
            if (!$user = JWTAuth::toUser($token)) {
                return response()->json([
                    'code' => Response::HTTP_UNAUTHORIZED,
                    'message' => 'User is not existed',
                    'data' => []
                ], Response::HTTP_UNAUTHORIZED);
            }
        } catch (TokenExpiredException $e) {
            return response()->json([
                'code' => Response::HTTP_UNAUTHORIZED,
                'message' => 'Token is expired',
                'data' => []
            ], Response::HTTP_UNAUTHORIZED);

        } catch (TokenInvalidException $e) {
            return response()->json([
                'code' => Response::HTTP_UNAUTHORIZED,
                'message' => 'Token is invalid',
                'data' => []
            ], Response::HTTP_UNAUTHORIZED);
        } catch (JWTException $e) {
            return response()->json([
                'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Jwt unknown exception',
                'data' => []
            ], Response::HTTP_UNAUTHORIZED);
        }

        return $next($request);
    }
}
